package com.gexin.core.interceptor;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import com.gexin.common.WebConst;
import com.gexin.common.model.AjaxCmd;
import com.gexin.common.model.ApiResponse;
import com.gexin.common.utils.StringUtil;
import com.gexin.model.system.AdminUser;
import com.gexin.model.system.RoleKit;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.core.JFinal;
import com.jfinal.log.Log;

/**
 * 系统管理员的拦截器
 * 
 * @author 肖得明 2018-04-24
 */
public class SystemAuthInterceptor implements Interceptor {
	private static final Log log = Log.getLog(SystemAuthInterceptor.class);

	@Override
	public void intercept(Invocation paramInvocation) {
		Controller controller = paramInvocation.getController();

		AdminUser user = controller.getSessionAttr(WebConst.Session_SysUser);
		// System.err.println( paramInvocation.getActionKey()+paramInvocation.getController().+paramInvocation.getController().getRequest().getQueryString());
		// 判断等于空的时候 没有登录
		if (user == null) {
			if (isAjax(controller.getRequest())) {
				paramInvocation.getController().renderJson(new ApiResponse(false, "登陆超时请刷新当前页面！"));
			} else {
				StringBuffer buf = new StringBuffer(paramInvocation.getActionKey());
				String par = paramInvocation.getController().getPara();
				if (StringUtil.isNotBlank(par)) {
					buf.append("/").append(par);
				}
				par = paramInvocation.getController().getRequest().getQueryString();
				if (StringUtil.isNotBlank(par)) {
					buf.append("?").append(par);
				}
				// System.err.println(buf.toString());
				try {
					controller.redirect("/system/login?go=" + URLEncoder.encode(buf.toString(), "UTF-8"));
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} else {
			// 不是超级管理员就判断权限
			if (user.getRoleId() != -1) {
				// 判断如果这个菜单在权限里面有没限制 有就判断这个用户有没这个权限
				if (RoleKit.ResMap.containsKey(paramInvocation.getActionKey())) {
					if (!RoleKit.checkRole(user.getId(), paramInvocation.getActionKey())) {
						// 没有权限
						if (isAjax(controller.getRequest()))
							paramInvocation.getController().renderJson(new ApiResponse(false, "您没有权限访问！"));
						else
							controller.renderError(401);
						return;
					}
				}
			}
			controller.setAttr(WebConst.Session_SysUserId, user.getId());
			// controller.setAttr("activite_index", RoleKit.getResMap(paramInvocation.getActionKey()));//获取样式的索引给前端焦点选择
			// 拦截统一异常信息
			try {
				paramInvocation.invoke();
			} catch (Exception e) {
				doLog(paramInvocation, e);
				// 判断如果是ajax 请求给出响应
				if (isAjax(controller.getRequest())) {
					paramInvocation.getController().renderJson(new AjaxCmd(false, "服务器异常请稍后再试！"));
				} else {
					paramInvocation.getController().renderError(500);
				}
			}
		}

	}

	private boolean isAjax(HttpServletRequest request) {
		String requtype = request.getHeader("X-Requested-With");
		if (StringUtil.isNotBlank(requtype)) {
			if (requtype.equals("XMLHttpRequest")) {
				return true;
			}
		}
		return false;
	}

	private void doLog(Invocation ai, Exception e) {
		// 开发模式
		if (JFinal.me().getConstants().getDevMode()) {
			e.printStackTrace();
		}
		StringBuilder sb = new StringBuilder("\n---Exception Log Begin---\n");
		sb.append("Controller:").append(ai.getController().getClass().getName()).append("\n");
		sb.append("Method:").append(ai.getMethodName()).append("\n");
		sb.append("Exception Type:").append(e.getClass().getName()).append("\n");
		sb.append("Exception Details:");
		log.error(sb.toString(), e);
	}

}
